// Copyright Epic Games, Inc. All Rights Reserved.

#include "zenhttp/httpstats.h"

#include <zencore/compactbinarybuilder.h>

namespace zen {

HttpStatsService::HttpStatsService() : m_Log(logging::Get("stats"))
{
}

HttpStatsService::~HttpStatsService()
{
}

const char*
HttpStatsService::BaseUri() const
{
	return "/stats";
}

void
HttpStatsService::RegisterHandler(std::string_view Id, IHttpStatsProvider& Provider)
{
	RwLock::ExclusiveLockScope _(m_Lock);
	m_Providers.insert_or_assign(std::string(Id), &Provider);
}

void
HttpStatsService::UnregisterHandler(std::string_view Id, IHttpStatsProvider& Provider)
{
	ZEN_UNUSED(Provider);

	RwLock::ExclusiveLockScope _(m_Lock);
	m_Providers.erase(std::string(Id));
}

void
HttpStatsService::HandleRequest(HttpServerRequest& Request)
{
	using namespace std::literals;

	std::string_view Key = Request.RelativeUri();

	switch (Request.RequestVerb())
	{
		case HttpVerb::kHead:
		case HttpVerb::kGet:
			{
				if (Key.empty())
				{
					CbObjectWriter Cbo;

					Cbo.BeginArray("providers");

					{
						RwLock::SharedLockScope _(m_Lock);
						for (auto& Kv : m_Providers)
						{
							Cbo << Kv.first;
						}
					}

					Cbo.EndArray();

					Request.WriteResponse(HttpResponseCode::OK, Cbo.Save());
				}

				if (Key[0] == '/')
				{
					Key.remove_prefix(1);
					size_t SlashPos = Key.find_first_of("/?");
					if (SlashPos != std::string::npos)
					{
						Key = Key.substr(0, SlashPos);
					}

					RwLock::SharedLockScope _(m_Lock);
					if (auto It = m_Providers.find(std::string{Key}); It != end(m_Providers))
					{
						return It->second->HandleStatsRequest(Request);
					}
				}
			}

			[[fallthrough]];
		default:
			return;
	}
}

}  // namespace zen
